package net.wesley.android;

import java.io.IOException;
import java.net.URLEncoder;
import net.wesley.android.R;
import net.yebaihe.sdk.Base64;
import net.yebaihe.sdk.HttpConnection;
import net.yebaihe.sdk.SdkUtils;
import net.youmi.android.AdManager;
import net.youmi.android.appoffers.AppOffersManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class weizhang extends Activity implements OnQueryComplete {
	public static final String PREFS_NAME = "WeiZhangPrefsFile";
	private static final int NO_IMPLEMETATION = 1; //没有任何关于这个车牌的实现方法，不知需要哪些信息。
	private static final int IMPLEMENTATING = 2; //正在实现，已经确定知道需要哪些信息。
	private static final int IMPLEMENTATED = 3;//已经实现，输入信息以后即可查询。
	private static final String UrlBase = "http://lily.newim.net/appstore/wzcx.php?";
	protected static final int POINTS_SINGLE_DAY = 2;
	
	static{
		//第一个参数为您的应用发布Id
		//第二个参数为您的应用密码
		//第三个参数是请求广告的间隔，有效的设置值为30至200，单位为秒
		//第四个参数是设置测试模式，设置为true时，可以获取测试广告，正式发布请设置此参数为false
		AdManager.init("646f823f3ddb3c3d", "10e7a2bca1fbb6d1", 30, false);
	}

    protected String rid="";
	protected int dialogid=0;
	private View progress;
	private FrameLayout frame;
	private String code;
	private ImageView codeimgview;
	private Handler r3handler=new Handler(){
		public void handleMessage(Message message){
			switch (message.what){
			case HttpConnection.DID_ERROR://DID ERROR
				break;
			case HttpConnection.DID_SUCCEED://DID SUCC
    			Log.d("myown", "body"+message.obj);
				break;
			}
		}
	};
	private TableLayout paramTable=null;
	private Handler mode1handler=new Handler(){
		public void handleMessage(Message message){
    		EditText text=(EditText) findViewById(R.id.edt_chepai);
        	Button me = (Button) findViewById(R.id.btnsearch);
			switch (message.what){
			case HttpConnection.DID_ERROR://DID ERROR
				unlockinput();
				onComplete(-1,"ret:网络错误");
				break;
			case HttpConnection.DID_SUCCEED://DID SUCC
				String body=(String) message.obj;
				Log.d("myown", "srver say:"+body);
				body=body.trim();
				if (body.equals("no")){//一般的
					unlockinput();
    				showGetPoint();
				}
				else if (body.trim().equals("ok")){
					saveInfoPref();
					doQuery();
				}
				else if (body.trim().length()>0){
					unlockinput();
					new AlertDialog.Builder(weizhang.this).setIcon(R.drawable.icon)
					.setMessage(body.trim())
					.setTitle("信息")
					.create().show();
				}
				else{
					doQuery();
				}
				break;
			}
		}
	};
	protected Handler r4handler=new Handler(){
		public void handleMessage(Message message){
			onComplete(-2,"");
		}
	};
	private Handler r5handler=new Handler(){
		public void handleMessage(Message message){
			onComplete(-3,"");
		}
	};
	private Handler mode4handler=new Handler(){
		public void handleMessage(Message message){
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
			SharedPreferences.Editor editor = settings.edit();  
			editor.putBoolean("unlockinformed", true);  
			editor.commit(); 
		}
	};
	private boolean unlocked=false;
	/**
	 * 返回当前程序版本名
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			//Log.e("VersionInfo", "Exception", e);
		}
		return versionName;
	}	
	
  	protected void unlockinput() {
		EditText text=(EditText) findViewById(R.id.edt_chepai);
    	Button me = (Button) findViewById(R.id.btnsearch);
    	me.setEnabled(true);
    	text.setEnabled(true);
		frame.removeView(progress);
	}

	protected void showGetPoint() {
		final int total=AppOffersManager.getPoints(weizhang.this);
  		new AlertDialog.Builder(this).setTitle("需要积分支持")
  			.setMessage("您觉得这个软件有用吗？请通过积分支持本软件，积分的获取是免费的，您可以选择查询一次扣除10个积分或者一次性扣除300个积分永久解锁两种方式，您的选择是？")
  			.setPositiveButton("300个积分永久解锁", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					if (total>=300){
						if (AppOffersManager.spendPoints(weizhang.this ,300)){
							saveInfoPref();
							doInfo();
							showSucc("积分扣取成功，点击确定继续您的查询.");
						}
						else{
							showSpendFail("很抱歉，扣取积分失败，请重试!");
						}
					}
					else{
						showSpendFail(String.format("很抱歉，您的积分(%d)不足，请先免费获取更多积分",total));
					}
				}
			})
			.setNegativeButton("10个积分查询一次", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					if (total>=10){
						if (AppOffersManager.spendPoints(weizhang.this ,10)){
							showSucc("积分扣取成功，点击确定继续您的查询.");
						}
						else{
							showSpendFail("很抱歉，扣取积分失败，请重试!");
						}
					}
					else{
						showSpendFail(String.format("很抱歉，您的积分(%d)不足，请先免费获取更多积分",total));
					}
				}
			})
			.setNeutralButton("免费获取积分", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					AppOffersManager.showAppOffers(weizhang.this);
				}
			}).setIcon(R.drawable.icon).create().show();
	}

	protected void doInfo() {
    	String url=UrlBase+"mode=4&imei="+SdkUtils.getIMEI(this);
    	new HttpConnection(this,mode4handler).get(url);
	}

	protected void saveInfoPref() {
		unlocked=true;
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
		SharedPreferences.Editor editor = settings.edit();  
		editor.putBoolean("unlocked", true);  
		editor.putBoolean("unlockinformed", false);  
		editor.commit(); 
	}

	protected void showSucc(String string) {
		new AlertDialog.Builder(this).setTitle("积分成功扣除").setMessage(string)
			.setPositiveButton("继续查询", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					doQuery();
				}
			}).setIcon(R.drawable.icon).create().show();
	}

	protected void showSpendFail(String string) {
		new AlertDialog.Builder(this).setTitle("积分扣取失败").setMessage(string)
		.setPositiveButton("确定", null).setIcon(R.drawable.icon)
					.setNeutralButton("免费获取积分", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					AppOffersManager.showAppOffers(weizhang.this);
				}
			})
		.create().show();
	}

	protected void doQuery() {
		EditText text=(EditText) findViewById(R.id.edt_chepai);
    	String chepai=text.getText().toString();
    	City city=CityManager.getCity(chepai);
    	if (city!=null){
    		city.doQuery(this,chepai,this);
    	}
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        AppOffersManager.init(this,"646f823f3ddb3c3d","10e7a2bca1fbb6d1",false);
        
        //showToast(getAppVersionName(this));
        frame=new FrameLayout(this);

        LayoutInflater factory = LayoutInflater.from(this);
        View textEntryView = factory.inflate(R.layout.main, null);
        frame.addView(textEntryView);
        
        progress=factory.inflate(R.layout.progress, null);
        
        setContentView(frame);
        Button twoButtonsTitle = (Button) findViewById(R.id.btnsearch);
        twoButtonsTitle.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
				InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				in.hideSoftInputFromWindow(v.getApplicationWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
            	doSearch();
            }
        });
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
        String chepai = settings.getString("chepai",getString(R.string.default_chepai));  
		EditText text=(EditText) findViewById(R.id.edt_chepai);
		text.setText(chepai);
		text.setSingleLine();
		text.setOnKeyListener(new OnKeyListener(){
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode==KeyEvent.KEYCODE_ENTER){
					InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					in.hideSoftInputFromWindow(v.getApplicationWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
					doSearch();
				}
				return false;
			}});		
		TextView v=(TextView)findViewById(R.id.retview);
		v.setText(Html.fromHtml(getString(R.string.help)));

		unlocked=settings.getBoolean("unlocked",false);
		if (unlocked){
			Log.d("myown", "unlocked!!");
		}
        boolean unlockinformed = settings.getBoolean("unlockinformed",true);  
        if (!unlockinformed){
        	doInfo();
        }
		
    }

	protected void doSearch() {
		EditText text=(EditText) findViewById(R.id.edt_chepai);
		if (text.getText().toString().length()!=7){
			Toast.makeText(this, "车牌号码应该为七位，比如：晋A12345，请重新输入", Toast.LENGTH_LONG).show();
			return;
		}
		
		text.setText(text.getText().toString().toUpperCase());
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
		SharedPreferences.Editor editor = settings.edit();  
		editor.putString("chepai", text.getText().toString());  
		editor.commit(); 
		
		lockinput();
    	
    	String chepai=text.getText().toString();
    	String url=UrlBase+"chepai="+URLEncoder.encode(chepai);
    	int status=getStatusFromChePai(chepai);
    	switch (status){
    	case NO_IMPLEMETATION:
    		//发送车牌数据到服务器，弹出提示窗口。
    		url+="&result=-3";
        	new HttpConnection(this,r5handler).get(url);
        	onComplete(-3, "");
    		break;
    	case IMPLEMENTATING:
    		//弹出对话框提示正在采集本城市的样本数据，询问是否愿意提供数据帮助尽快实现该城市的支持，如果愿意则收集信息，发送到服务器，感谢配合
    		showHelpMeDialog(chepai);
    		break;
    	case IMPLEMENTATED:
    		//询问服务器该手机是否在服务期内，如果在，询问相关信息后查询并显示结果。如果不在，提示用积分换取服务，下载积分以后消费积分的个数由用户自己决定。
        	if (unlocked){
        		doQuery();
        	}
        	else{
        		url+="&mode=1&useok=1";
        		new HttpConnection(this,mode1handler).get(url);
        	}
    		break;
    	}
	}

	private void lockinput() {
		EditText text=(EditText) findViewById(R.id.edt_chepai);
    	Button me = (Button) findViewById(R.id.btnsearch);
    	me.setEnabled(false);
		frame.addView(progress);
    	text.setEnabled(false);  
	}

	private void showHelpMeDialog(String chepai) {
		String[]descs= getParamsDesc(chepai);
		final String pai=chepai;
		if ((descs!=null) && (descs.length>0)){
			Builder build = new AlertDialog.Builder(this).setIcon(R.drawable.icon)
			.setTitle("请输入以下信息：")
			.setNegativeButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					String url=UrlBase+"chepai="+URLEncoder.encode(pai)+"&result=-2";
			    	SharedPreferences settings = weizhang.this.getSharedPreferences(weizhang.PREFS_NAME, 0);  
					SharedPreferences.Editor editor = settings.edit();  
					for (int i=0;i<paramTable.getChildCount();i++){
						TableRow r=(TableRow) paramTable.getChildAt(i);
						String v=((EditText)r.getChildAt(1)).getText().toString();
						url+="&p"+(i+1)+"="+URLEncoder.encode(v);
						editor.putString(pai+"p"+i, v);  
					}
					editor.commit(); 
					new HttpConnection(weizhang.this,r4handler).get(url);
				}
			});
			paramTable=City.updateParams(this,chepai,build,descs);
			build.create().show();
		}
	}

	private String[] getParamsDesc(String chepai) {
		return CityManager.getParamDesc(chepai);
	}

	private int getStatusFromChePai(String chepai) {
		if (CityManager.isFinished(chepai)){
			return IMPLEMENTATED;
		}
		if (CityManager.isFinishing(chepai)){
			return IMPLEMENTATING;
		}
		return NO_IMPLEMETATION;
	}

	protected void processCommonResult(String result) {
		if (result.startsWith("ret:")){
			if (result.substring(4).trim().startsWith("more")){
				processMore(result);
			}
			else{
				showToast(result.substring(4));
				TextView v=(TextView)findViewById(R.id.retview);
				v.setText(Html.fromHtml(result.substring(4)));
			}
		}
		else{
			processResult(result);
		}
	}

	private void showToast(String substring) {
		Toast t=Toast.makeText(weizhang.this, substring, Toast.LENGTH_LONG);
		t.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 70);
		t.show();
	}

	private void processResult(String result) {
		result=result.trim();
		if (result.length()<=0){
			showToast("就我们所知的:什么违章都没有");
			return;
		}
		String[] results = result.trim().split("\n\n");
		showToast("共查到您有"+results.length+"次违章");
		String ret="";
		for (int i=0;i<results.length;i++){
			String[] cols = results[i].split("\n");
			for (int j=0;j<cols.length;j++){
				if (cols[j].split(":")[0].equals("shijian")){
					ret+="<font color=\"#0000FF\">"+cols[j].substring(cols[j].indexOf(":")+1)+"</font>：";
				}
				else if (cols[j].split(":")[0].equals("code")){
					ret+="&nbsp;&nbsp;&nbsp;"+cols[j].substring(cols[j].indexOf(":")+1)+"<p/>";
				}
				else{
					ret+=cols[j].substring(cols[j].indexOf(":")+1);
				}
			}
		}
		Log.d("this", ret);
		TextView v=(TextView)findViewById(R.id.retview);
		v.setText(Html.fromHtml(ret));
	}

    @Override
	protected void onPrepareDialog(int id, Dialog dialog){
		if ((id==4) || (id==5)){
	        try { 
	            byte[] bitmapArray; 
	            bitmapArray = Base64.decode(code); 
	            Bitmap bmp= BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length); 
	            codeimgview.setImageBitmap(bmp);
	        } catch (IOException e) { 
	            e.printStackTrace(); 
	        } 
		}
	}

	private void processMore(String result) {
		String desc=result.split("\n\n")[1];
		String[] descrows = desc.split("\n");
		for (int i=0;i<descrows.length;i++){
			String[] keyvalue = descrows[i].split(":");
			String key=keyvalue[0];
			String value=keyvalue[1];
			if (key.equals("rid")){
				rid=value;
			}
			else if (key.equals("dialogid")){
				dialogid=Integer.parseInt(value);
			}
			else if (key.equals("code")){
				code=value;
			}
		}
		showDialog(dialogid);
	}

	public void onComplete(int result, String detail) {
		EditText text=(EditText) findViewById(R.id.edt_chepai);
    	String url=UrlBase+"chepai="+URLEncoder.encode(text.getText().toString())+"&result="+result;
        SharedPreferences settings = getSharedPreferences(weizhang.PREFS_NAME, 0);  
        for (int i=0;i<3;i++){
	        String v0 = settings.getString(text.getText().toString()+"p"+i,"");  
	        url+="&p"+(i+1)+"="+URLEncoder.encode(v0);
        }

    	if ((result>-2) || (result<-3)){
    		Log.d("myown", url);
    		new HttpConnection(this,r3handler).get(url);
    	}
    	else{
    		if (result==-3){
    			Toast.makeText(this, "您所在的城市目前还不被支持，请关注后续升级版本。", Toast.LENGTH_LONG).show();
    			return;
    		}
    		else if (result==-2){
    			Toast.makeText(this, "您所在的城市将很快被支持，请关注后续升级版本。", Toast.LENGTH_LONG).show();
    			return;
    		}
    	}
		if ((detail!=null) && (detail.length()>0)){
			processCommonResult(detail);
		}
		else{
			if (result==0){
				Toast.makeText(this, "恭喜您，暂时没有任何违章记录", Toast.LENGTH_LONG).show();
			}
			else{
				String hint="对不起，出错了，错误代码："+result;
		    	if ((result>-2) || (result<-3)){
		    		hint+="，请稍后重试！";
		    	}
				Toast.makeText(this, hint, Toast.LENGTH_LONG).show();
			}
		}
    	Button me = (Button) findViewById(R.id.btnsearch);
    	me.setEnabled(true);
    	text.setEnabled(true);
		frame.removeView(progress);
	}	
	
	@Override
	public void onBackPressed(){
		super.onBackPressed();
		finish();
	}
}